package org.example.reactor;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class AcceptHandler implements Runnable {

    private ServerSocketChannel server;

    private Selector selector;

    public AcceptHandler(ServerSocketChannel server, Selector selector) {
        this.server = server;
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            // 获取新连接
            SocketChannel socketChannel = server.accept();
            socketChannel.configureBlocking(false);

            SelectionKey selectionKey = socketChannel.register(selector, 0);

            selectionKey.attach(new EchoHandler(selectionKey));
            selectionKey.interestOps(SelectionKey.OP_READ);

            // 唤醒selector.select()方法
            selector.wakeup();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
